package com.kd.common;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;

public class IpUtils {
    // 预编译IPv6和IPv4正则表达式（提升性能）
    private static final Pattern IPV6_PATTERN = Pattern.compile(
            "^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|" +
                    "([0-9a-fA-F]{1,4}:){1,7}:|" +
                    "([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|" +
                    "([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|" +
                    "([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|" +
                    "([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|" +
                    "([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|" +
                    "[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|" +
                    ":((:[0-9a-fA-F]{1,4}){1,7}|:)|" +
                    "fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|" +
                    "::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|" +
                    "([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$"
    );

    private static final Pattern IPV4_PATTERN = Pattern.compile(
            "^((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.){3}(25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)$"
    );

    // 改为public static，允许外部调用
    public static String getIp(HttpServletRequest request) {
        // 空指针防护：若request为null，直接返回unknown
        if (request == null) {
            System.out.println("HttpServletRequest为null，无法获取IP");
            return "unknown";
        }

        String ip = null;
        String[] headers = {
                "X-Real-IP",
                "X-Forwarded-For",
                "Proxy-Client-IP",
                "WL-Proxy-Client-IP"
        };

        for (String header : headers) {
            String headerIp = request.getHeader(header);
            if (headerIp != null && !headerIp.isEmpty() && !"unknown".equalsIgnoreCase(headerIp)) {
                String[] ips = headerIp.split(",");
                for (String tempIp : ips) {
                    tempIp = tempIp.trim();
                    if (isIPv6(tempIp)) {
//                        System.out.println("获取到IPv6地址: " + tempIp);
                        return tempIp;
                    }
                    if (ip == null && isIPv4(tempIp)) {
//                        System.out.println("获取到IPv4地址: " + tempIp);
                        ip = tempIp;
                    }
                }
            }
        }

        if (ip == null) {
            String remoteIp = request.getRemoteAddr().trim();
            if (isIPv6(remoteIp)) {
                System.out.println("从原始请求获取到IPv6地址: " + remoteIp);
                return remoteIp;
            } else if (isIPv4(remoteIp)) {
                System.out.println("从原始请求获取到IPv4地址: " + remoteIp);
                ip = remoteIp;
            }
        }
        String result = ip != null ? ip : "unknown";
        System.out.println("最终获取的IP地址: " + result);
        return result;
    }

    // 改为private static，工具类内部调用
    private static boolean isIPv6(String ip) {
        if (ip == null || ip.isEmpty()) {
            return false;
        }
        return IPV6_PATTERN.matcher(ip).matches();
    }

    // 改为private static，工具类内部调用
    private static boolean isIPv4(String ip) {
        if (ip == null || ip.isEmpty()) {
            return false;
        }
        return IPV4_PATTERN.matcher(ip).matches();
    }
}
